package net.sunxiaolong.tool.captureinsureknowledge.tool.capture;

import net.sunxiaolong.tool.captureinsureknowledge.entity.GpicKnowledge;
import net.sunxiaolong.tool.captureinsureknowledge.repository.GpicKnowledgeRepository;
import net.sunxiaolong.tool.captureinsureknowledge.tool.NetworkTool;
import net.sunxiaolong.tool.captureinsureknowledge.tool.SnowFlakeIdGenerator;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 晓龙
 * @create 2018-08-14 下午2:09
 * @desc
 **/
@Component
public class GpicCapture {

    private static GpicKnowledgeRepository gpicKnowledgeRepository;

    public GpicCapture() {
    }

    @Autowired
    public GpicCapture(GpicKnowledgeRepository gpicKnowledgeRepository) {
        GpicCapture.gpicKnowledgeRepository = gpicKnowledgeRepository;
    }

    public static void capture(String pageUrlStr) throws XPatherException {
        String pageContent = NetworkTool.getStringFromUrl(pageUrlStr, null);
        TagNode pageTn = new HtmlCleaner().clean(pageContent);
        String liPathStr = "//li[@class='questiontit']";
        String currentPageAStr = "//div[@class='pages']/div[@class='tit']/div[@class='pages']/a[@class='current']";
        String nextPageAStr = "//div[@class='pages']/div[@class='tit']/div[@class='pages']/a[@class='page_down']";

        int currentPage = Integer.parseInt(((TagNode) pageTn.evaluateXPath(currentPageAStr)[0]).getText().toString());
        TagNode nextPageATn = (TagNode) pageTn.evaluateXPath(nextPageAStr)[0];
        String nextStr = nextPageATn.getAttributeByName("onclick");

        Object[] liObjArray = pageTn.evaluateXPath(liPathStr);
        List<GpicKnowledge> gkList = new ArrayList<>();
        for (int i = 0; i < liObjArray.length; i++) {
            TagNode thisLiTn = (TagNode) liObjArray[i];
            String questionPathStr = "//div[@class='qutit']/a/span";
            String answerPathStr = "//div[@class='answertxt']/div[@class='txt']";
            String thisQuestion = ((TagNode) thisLiTn.evaluateXPath(questionPathStr)[0]).getText().toString();
            String thisAnswer = ((TagNode) thisLiTn.evaluateXPath(answerPathStr)[0]).getText().toString().replace("解答：", "").replaceAll("&nbsp;", "").trim();
            GpicKnowledge gk = new GpicKnowledge(SnowFlakeIdGenerator.nextId(), thisQuestion, thisAnswer, pageUrlStr);
            gkList.add(gk);
        }
        gpicKnowledgeRepository.saveAll(gkList);
        if (null != nextStr) {
            if (pageUrlStr.lastIndexOf("&curtPage") > -1) {
                pageUrlStr = pageUrlStr.substring(0, pageUrlStr.lastIndexOf("&curtPage"));
            }
            String nextHrefStr = pageUrlStr + "&curtPage=" + (currentPage + 1);
            capture(nextHrefStr);
        }
    }
}
